﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Heavysoft.Mince.Support;
using Heavysoft.Mince.Models;

namespace Heavysoft.Mince.Controllers
{
    public class PhotosController : Controller
    {
        //
        // GET: /Photos/

        public ActionResult Index()
        {
            ulong photosCount = CacheManager.Get<ulong>(Photo.KeyMaxId);
            object wtf = CacheManager.Get<object>(Photo.KeyMaxId);
            List<Photo> list = new List<Photo>();

            for (ulong i = 1; i < photosCount; ++i)
            {
                Photo tmp = CacheManager.Get<Photo>(CacheManager.MakeKey(Photo.KeyItem, i));
                if (tmp == null)
                    continue;

                list.Add(tmp);
            }

            return View(list);
        }

        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                ulong id = CacheManager.IncrementId(Photo.KeyMaxId);
                Photo photo = new Photo();
                photo.ID = id;

                string extension = System.IO.Path.GetExtension(file.FileName);

                string[] allowedExtension = { ".png", ".jpg" };

                if (!allowedExtension.Contains(extension))
                {
                    throw new InvalidOperationException("Wrong file extension");
                }

                string folder = Server.MapPath("~/App_Data/Photos/");
                if (!System.IO.Directory.Exists(folder))
                    System.IO.Directory.CreateDirectory(folder);

                
                photo.OriginalName = file.FileName;
                photo.Uri = "/Photos/" + id.ToString();

                CacheManager.Add(CacheManager.MakeKey(Photo.KeyItem, photo.ID), photo);

                file.SaveAs(folder + id.ToString());
            }

            return RedirectToAction("Index");
        }
    }
}
